package cn.bluedot.framework.web;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.Map;
import java.util.Map.Entry;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.alibaba.fastjson.JSON;

import cn.bluedot.framework.annotations.Dispatcher;
import cn.bluedot.framework.annotations.Redirect;
import cn.bluedot.framework.annotations.ResponseJson;

/**
 * 视图解析器
 * @author Administrator
 *
 */
public class ViewResolver {

	/**
	 * 视图解析
	 * @param handler
	 * @param req
	 * @param res
	 * @param data
	 * @throws IOException
	 * @throws ServletException
	 */
	public static void execute(RequestHandler handler, HttpServletRequest req, HttpServletResponse res,
			Map<String, Object> data) throws IOException, ServletException {
		
		Object result = data.get("Result");
		Method method = handler.getMethod();
		
		//处理重定向
		if(method.isAnnotationPresent(Redirect.class)) {
			
			Redirect redirect = method.getDeclaredAnnotation(Redirect.class);
			
			String target = null;
		
			if(Result.SUCCESS.equals(result)) {
				target = redirect.success();
			} else if(Result.FAILED.equals(result)) {
				target = redirect.failed();
			}
			
			res.sendRedirect(req.getContextPath()+target);
			return;
		}
		//处理JSON
		if(method.isAnnotationPresent(ResponseJson.class)) {
			res.getWriter().print(JSON.toJSON(data));
			return;
		}
		//处理转发
		if(method.isAnnotationPresent(Dispatcher.class)) {
			Dispatcher dispatcher = method.getDeclaredAnnotation(Dispatcher.class);
			
			String path = null;

			if(Result.SUCCESS.equals(result)) {
				path = dispatcher.success();
			} else if(Result.FAILED.equals(result)) {
				path = dispatcher.failed();
			}
			//将data中数据装入request域对象中
			for (Entry<String, Object> entry : data.entrySet()) {
				req.setAttribute(entry.getKey(), entry.getValue());
	        }
			
			req.getRequestDispatcher(path).forward(req, res);
			return;
		}
		
	}
	
	
}
